import React, { useState } from 'react';
import { sysUploadUrl } from '../../../../../../Api/fileUrl'
import { getLsCarLogoAddLogo } from '../../../../api'
import { Modal, Upload, message } from 'antd'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';

const AddLogModule = ({ setAddLogModuleShow, addLogModuleShow, listFun }) => {
    const [imageUrl, setImageUrl] = useState(undefined)
    const [loading, setLoading] = useState(false)
    const handleOk = () => {
        ;(async () => {
            const {code, msg } = await getLsCarLogoAddLogo({logo: imageUrl});
            if(code === '20000') {
                message.success('添加成功')
                listFun()
                setImageUrl(undefined);
                setAddLogModuleShow(false);
            }else{
                message.error(msg);
            }
        })()
        // setAddLogModuleShow(false);
    };

    const handleCancel = () => {
        setImageUrl(undefined);
        setAddLogModuleShow(false);
    };
    const beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('You can only upload JPG/PNG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
    }
    const handleUpload = info => {
        if (info.file.status === 'uploading') {
            setLoading(true)
            return;
        }
        if (info.file.status === 'done') {
            setLoading(false)
            setImageUrl(info.file.response.data)
        }
    }
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    return <Modal title="添加log" visible={addLogModuleShow} onOk={handleOk} onCancel={handleCancel}>
        <Upload
            name="file"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            action={sysUploadUrl()}
            beforeUpload={beforeUpload}
            headers={{
                authentication: sessionStorage.getItem("token")
            }}
            data={{ folder: '/logo' }}
            onChange={handleUpload}
        >
            {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
        </Upload>
    </Modal>
}

export default AddLogModule;